import store from '../vuex/store'



const ws = {
    wsServer:process.env.WS_API+"/websocket/",
    websocket:null,
    authws:'',
    connection:false,//是否连接成功
    interval:null,//重连定时器
    init:function (val) {
        var self = val;
        if(store.state.user.token){
          this.authws = this.wsServer+store.state.user.token;
        }
        this.websocket = new WebSocket(this.authws);
        this.websocket.onopen = function (evt) {
            ws.connection=true;
        };
        this.websocket.onclose = function (evt) {
            if(ws.connection){
              console.log('通信断开');
            //  Message({message:'通信断开',type: 'error'});
              ws.reconnection();
            }

        };
        this.websocket.onmessage = function (evt) {
                if(evt.data){
                    let socketMsg = JSON.parse(evt.data)
                     //console.log("socketMsg"+socketMsg);
                    if(socketMsg.positions){
                      // console.log("位置改变"+socketMsg);
                          store.dispatch('updateDevicePosition',socketMsg.positions);
                    }else if(socketMsg.devices){
                          store.dispatch('updateDeviceStatus', socketMsg.devices);
                    }else if(socketMsg.states){
                        // console.log("updateDeviceState"+socketMsg.states);
                        //  self.$store.dispatch('updateDeviceState', socketMsg.states);
                    }
                }
        };
        this.websocket.onerror = function (evt) {
        };
    },
    close:function(){
        this.websocket.close();

    },
    reconnection:function (val) {
        ws.connection=false;
        ws.interval =  setInterval(function () {
                      if (ws.connection) {
                        // window.f7.toast.create({
                        //    text:'重连成功',
                        //    closeTimeout: 2000,
                        //  }).open();
                          clearInterval(ws.interval);
                      } else {
                        // window.f7.toast.create({
                        //    text: '尝试重连',
                        //    closeTimeout: 2000,
                        //  }).open();
                          ws.connection=false;
                          ws.init(val);
                      }
                  }, 10000);
    }
}

export default ws
